package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.mapper.TbUserMapper;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.ResultResponse;
import com.bwie.utils.TokenUtils;
import com.bwie.vo.LoginVo;
import com.bwie.vo.ResetPassWordVo;
import com.bwie.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class TbUserServiceImpl implements TbUserService{

    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public ResultResponse userLogin(LoginVo loginVo) {
        TbUser tbUser = tbUserMapper.selectOne(new LambdaQueryWrapper<TbUser>().eq(TbUser::getUsername, loginVo.getUserName()).last("limit 1"));
        if (tbUser==null){
            return ResultResponse.failed(404,"用户不存在");
        }
        if (!tbUser.getPassword().equals(loginVo.getPassWord())){
            return ResultResponse.failed(403,"密码错误");
        }
        // token的过期时间建议要比redis的过期时间要长一点
        String token = TokenUtils.token().setKey("123456").setExpire(60 * 30).createToken("userId", "" + tbUser.getId(), "userName", tbUser.getUsername());

        String key="pc"+tbUser.getId();

        redisTemplate.opsForValue().set(key,token,30, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(token,token,30, TimeUnit.MINUTES);

        //返回用户信息
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(tbUser,userInfoVo);
        userInfoVo.setToken(token);
        return ResultResponse.success(userInfoVo);
    }

    @Override
    public ResultResponse userResetPassWord(ResetPassWordVo resetPassWordVo) {
        //获取用户信息
        TbUser tbUser = tbUserMapper.selectById(resetPassWordVo.getUserId());
        if (tbUser==null) {
            return ResultResponse.failed(404,"用户不存在");
        }
        //比较密码
        if (!tbUser.getPassword().equals(resetPassWordVo.getOldPass())){
            return ResultResponse.failed(403,"密码不正确");
        }
        //修改密码
        tbUser.setPassword(resetPassWordVo.getNewPass());
        tbUserMapper.updateById(tbUser);
        //返回信息
        return ResultResponse.success();
    }
}




